package com.woniuxy.intellihome.controller.front;


import com.woniuxy.intellihome.entity.*;
import com.woniuxy.intellihome.service.OrderService;
import com.woniuxy.intellihome.service.OrderitemService;
import com.woniuxy.intellihome.service.UserService;
import com.woniuxy.intellihome.utils.UtilsTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author pengZhihong
 * @since 2021-08-18
 * 1、前台订单页面跳转
 */
@Slf4j
@Controller("/front/order")
@RequestMapping("/front/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderitemService orderitemService;
    @Autowired
    private UserService userService;

    /**
     * 页面跳转至orders
     *
     * @return
     */
    @GetMapping("/list")
    public String list(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user1");
        model.addAttribute("user", user);
        return "Orders";
    }

    /**
     * 页面跳转至orders_check 页面
     *
     * @return
     */
    @GetMapping("/check")
    public String check(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user1");
        model.addAttribute("user", user);
        return "Orders_check";
    }

    /**
     * 将前台下单订单存入数据库
     *
     * @param order 前台发送order对象
     * @return JSON语句
     */
    @PostMapping("/add")
    @ResponseBody
    public ResponseEntity add(@RequestBody Order order, BindingResult result, HttpSession session) {
        //创建JSON返回语句对象
        ResponseEntity responseEntity = new ResponseEntity();
        //获取当前用户
        User user = (User) session.getAttribute("user1");
        //检查是否存在错误
        if (result.hasFieldErrors()) {
            //不存在返回无效提示
            Map<String, String> msgs = new HashMap<>();
            result.getFieldErrors().forEach(e -> {
                msgs.put(e.getField(), e.getDefaultMessage());
            });
            responseEntity.setCode(ResponseState.INVALIDARGS);
            responseEntity.setMsg("无效参数");
            responseEntity.setData(msgs);
        } else {

            try {
                //录入order
                //写入订单编号与下单时间
                order.setOrderNum(UtilsTools.getOrderNum());
                order.setOrderTime(UtilsTools.getTimeNow());
                order.setUserId(user.getId());
                System.out.println(order);
                orderService.add(order);
                //增加orderitem
                order.getCarts().forEach(cart -> {
                    Orderitem orderitem = new Orderitem();
                    orderitem.setSkuId(cart.getSkuId());
                    orderitem.setOrderId(order.getId());
                    orderitem.setMount(cart.getMount());
                    orderitem.setPrice(cart.getPrice());
                    orderitemService.save(orderitem);
                });

                //order添加成功，返回order对象
                responseEntity.setCode(200);
                responseEntity.setMsg("数据库添加成功");
                responseEntity.setData(order);
            } catch (Exception e) {
                e.printStackTrace();
                responseEntity.setCode(500);
                responseEntity.setMsg("后台执行出错，请检查");
            }
        }
        return responseEntity;
    }

}

